//
//  SearchVController.m
//  Experss
//
//  Created by 嗯，大葱 on 17/7/31.
//  Copyright © 2017年 嗯，大葱. All rights reserved.
//

#import "SearchVController.h"
#import "TextFiledAddImage.h"
#import "SeachOneCell.h"
#import "fenLeiDetailViewController.h"

@interface SearchVController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
{
    
    UITextField *seachField;
    
    
    //显示用户的历史记录
    NSMutableArray *_historyArr;
    
    
    //单例
    NSUserDefaults *_defaults;
    
}
@property (nonatomic, strong)  UIButton *tempBtn;
@property (nonatomic, strong)  UITableView *tableView;
//@property (nonatomic, strong)


@property (nonatomic, strong)UIButton *rightBtn;

@property (nonatomic, strong)NSArray *hotListArry;

@end

@implementation SearchVController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configureNaVC];//配置导航栏
    [self getHotSeachData];//获取热门搜索数据
    [self configureSecondView];//配置第二个view;
    //创建单例对象和接受字符串的数组和表
    [self _createUserStand];
}
#pragma mark 获取热门搜索数据
- (void)getHotSeachData {
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    NSDictionary *parameDic = @{@"userid":saveDic[@"userid"],@"actoken":[Md5Apiway getMD5data:saveDic[@"userid"]]};
    [HttpRequest getWithURLString:POST(Shop_HomeGetHotSearch) parameters:parameDic success:^(id responseObject) {
        if ([responseObject[@"ret"] intValue] != 200) {
            [MBProgressHUD showText:@"获取热门搜索出错"];
            return ;
        }
        NSDictionary *tempD = responseObject[@"data"];
        
        if (![[NSString stringWithFormat:@"%@",tempD[@"code"]] isEqualToString:@"0"]) {
            [MBProgressHUD showText:tempD[@"msg"]];
            return;
        }
        
        _hotListArry = responseObject[@"data"][@"list"];
        CGFloat maxY = CGRectGetMaxY(_hotLabel.frame);
        CGFloat w = 0;//保存前一个button的宽以及前一个button距离屏幕边缘的距离
        CGFloat h = maxY+10;//用来控制button距离父视图的高
   
        
        for (int i = 0; i < _hotListArry.count; i++) {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
            button.tag = 100 + i;
            button.backgroundColor = KShouYeBg;
            //[button addTarget:self action:@selector(handleClick:) forControlEvents:UIControlEventTouchUpInside];
            [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            //根据计算文字的大小
            
            [button addTarget:self action:@selector(handleTureGoodList:) forControlEvents:(UIControlEventTouchUpInside)];
            NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:12]};
            CGFloat length = [_hotListArry[i] boundingRectWithSize:CGSizeMake(320, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.width;
            //为button赋值
            [button setTitle:_hotListArry[i] forState:UIControlStateNormal];
            button.layer.masksToBounds = YES;
            button.layer.cornerRadius = 15;
            //设置button的frame
            button.frame = CGRectMake(20 + w, h, length + 40 , 30);
            //当button的位置超出屏幕边缘时换行 320 只是button所在父视图的宽度
            if(10 + w + length + 15 > 320){
                w = 0; //换行时将w置为0
                h = h + button.frame.size.height + 10;//距离父视图也变化
                button.frame = CGRectMake(20 + w, h, length + 40, 30);//重设button的frame
            }
            w = button.frame.size.width + button.frame.origin.x;
            
            
            [self.bgV2 addSubview:button];
        }
        
        
    } failure:^(NSError *error) {
        
    }];

}

- (void)_createUserStand
{
    
    //创建单例
    _defaults = [NSUserDefaults standardUserDefaults];
    NSData *saveMenulistDaate = [_defaults objectForKey:@"searchArrayData"];
    
    //为空，创建数组，不为空，提取数组
    if (saveMenulistDaate == nil) {
        
        _historyArr = [NSMutableArray array];
        
    }else{
        
        _historyArr = (NSMutableArray *)[NSKeyedUnarchiver unarchiveObjectWithData:saveMenulistDaate];
    }
    
    
    
    // 将取出来的数组赋值给表
    [self _createSearchRecordTableViewWithArray:_historyArr];
    
    
    
}
- (void)_createSearchRecordTableViewWithArray:(NSMutableArray*)array
{
    
    
    if (array.count == 0) {
        
        _tableView.hidden = YES;
        
        
    }else{
        
        _tableView.hidden = NO;
        [_tableView reloadData];
    }
    
}//创建表

- (void)configureNaVC{
    UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg1"]];
    imgView.frame = self.bgView.bounds;
    imgView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [self.bgView insertSubview:imgView atIndex:0];
    
     [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"bg1"] forBarMetrics:UIBarMetricsDefault];
    seachField = [[UITextField alloc] initWithFrame:CGRectMake(50,22,kScreen_Width - 100, 30)];
    seachField.placeholder = @"搜索";
    seachField.backgroundColor = [UIColor colorWithWhite:0.969 alpha:1.000];
    seachField.font = [UIFont systemFontOfSize:14];
    
    seachField.layer.cornerRadius = CGRectGetHeight(seachField.frame)/2;
    seachField.layer.masksToBounds = YES;
    [self.bgView  addSubview:seachField] ;
    [TextFiledAddImage setLeftViewWithTextField:seachField imageName:@"fenlei_sousuo"];
    seachField.delegate = self;
    
    seachField.returnKeyType = UIReturnKeySearch;
    
    
    //设置导航栏按钮的边距
    _rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _rightBtn.frame= CGRectMake(0, 0, 60, 30);
    [_rightBtn setImage:[UIImage imageNamed:@"all_fanhui2"] forState:(UIControlStateNormal)];
    [_rightBtn addTarget:self action:@selector(onClickLeft) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *btn_left = [[UIBarButtonItem alloc] initWithCustomView:_rightBtn];
    UIBarButtonItem *negativeSpacerleft = [[UIBarButtonItem alloc]   initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace   target:nil action:nil];
    /**
     width为负数时，相当于btn向右移动width数值个像素，由于按钮本身和  边界间距为5pix，所以width设为-5时，间距正好调整为0；width为正数 时，正好相反，相当于往左移动width数值个像素
     */
    negativeSpacerleft.width = -20;
    self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects:negativeSpacerleft, btn_left, nil];
    
}
- (void)onClickLeft {
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    NSLog(@"++%@",textField.text);
}
//搜索按钮的点击事件
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSLog(@"点击了搜索%@",textField.text);
    //继续持久化
    NSData *historyData = [NSKeyedArchiver archivedDataWithRootObject:_historyArr];
    
    NSMutableArray *myHistoryArr = [[NSMutableArray alloc]init];
    
    if (historyData == nil)
    {
        
    }else{
        
        myHistoryArr = (NSMutableArray *)[NSKeyedUnarchiver unarchiveObjectWithData:historyData];
    }
    
    //去重复
    for (int i = 0; i < myHistoryArr.count; i++)
    {
        if ([textField.text isEqualToString:myHistoryArr[i]])
        {
            [myHistoryArr removeObjectAtIndex:i];
        }
        
    }
    
    //用户搜索历史记录
    [myHistoryArr insertObject:textField.text atIndex:0];
    
    
    //数组转化成data持久化
    NSData *encodemenulist = [NSKeyedArchiver archivedDataWithRootObject:myHistoryArr];
    [_defaults setObject:encodemenulist forKey:@"searchArrayData"];
    [_defaults synchronize];
    
    
    NSString *titleStr = [textField.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    /*
    SearchResultController *dia = [[SearchResultController alloc] init];
    UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:dia];
    dia.tempStr = titleStr;
    [self presentViewController:naVC animated:YES completion:nil];
     */
    return YES;
    
}


- (void)configureSecondView {
    
  
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 206, kScreen_Width, kScreen_Height - 100) style:(UITableViewStylePlain)];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.separatorStyle= UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    [self.tableView registerNib:[UINib nibWithNibName:@"SeachOneCell" bundle:nil] forCellReuseIdentifier:@"SeachOneCell"];
}
//计算热门文字所占大小
- (CGSize)getSizeByString:(NSString*)string AndFontSize:(CGFloat)font
{
    CGSize size = [string boundingRectWithSize:CGSizeMake(999, 25) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]} context:nil].size;
    size.width += 30;
    return size;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _historyArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *bgV = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    UIView *bgV2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, 39)];
    bgV2.backgroundColor = [UIColor whiteColor];
    
    bgV.backgroundColor = [UIColor colorWithRed:222/255.0 green:222/255.0 blue:222/255.0 alpha:0.5];
    UIButton *btn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    btn.frame = CGRectMake(CGRectGetWidth(bgV.frame) - 50, 0, 40, 40);
    [btn setImage:[UIImage imageNamed:@"sousuo_shanchu"] forState:(UIControlStateNormal)];
    [btn addTarget:self action:@selector(handleDeleteHostoryAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10,0, 100, 40)];
    label.text = @"历史搜索";
    label.textColor = [UIColor grayColor];
    label.font = kFont15;
    [bgV addSubview: bgV2];
    [bgV2 addSubview:label];
    [bgV2 addSubview:btn];
    
    return bgV;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SeachOneCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SeachOneCell"];
    cell.selectionStyle = kSeNone;
    cell.titlB.text = _historyArr[indexPath.row];
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    fenLeiDetailViewController *vc = [[fenLeiDetailViewController alloc] init];
    vc.tureTypeStr = @"search";
    vc.searchTitle = _historyArr[indexPath.row];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
- (IBAction)backBtnAction:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)handleDeleteHostoryAction:(UIButton *)sender {
    
  
    PVAlertView * alert = [PVAlertView sharedAlertView];
    [alert alertViewMessage:@"小通提示\n \n确定要删除历史搜索纪录吗\n" cancelTitle:@"取消" sureTitle:@"确定" image:nil Block:^{
        //移除所有的数据
        [_historyArr removeAllObjects];
        //继续持久化
        NSData *encodemenulist = [NSKeyedArchiver archivedDataWithRootObject:_historyArr];
        [_defaults setObject:encodemenulist forKey:@"searchArrayData"];
        [_defaults synchronize];
        //显示记录的表示图隐藏
        _tableView.hidden = YES;
        [seachField becomeFirstResponder];
    }];
  
    

}

#pragma mark - OverRide Methods
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    if (_historyArr.count == 0) {
        
        //成为第一响应者
        [seachField becomeFirstResponder];
        
    }else{
        
        [seachField resignFirstResponder];
    }
    
    [_tableView reloadData];
    //视图即将出现提取记录
    [self _createUserStand];
}//视图即将出现

- (void)viewWillDisappear:(BOOL)animated {
    self.navigationController.navigationBar.hidden = NO;
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;

}


- (IBAction)back2:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}



#pragma mark －＝－＝－＝－＝－＝搜索按钮的点击事件
//导航栏搜索按钮的点击事件
- (IBAction)searchBtnAction:(UIButton *)sender {
    if (seachField.text.length == 0) {
        [self.view showTextNoActivity:@"请输入搜索条件" timeLength:2.0];
        return;
    }
    NSLog(@"点击了搜索%@",seachField.text);
    //继续持久化
    NSData *historyData = [NSKeyedArchiver archivedDataWithRootObject:_historyArr];
    
    NSMutableArray *myHistoryArr = [[NSMutableArray alloc]init];
    
    if (historyData == nil)
    {
        
    }else{
        
        myHistoryArr = (NSMutableArray *)[NSKeyedUnarchiver unarchiveObjectWithData:historyData];
    }
    
    //去重复
    for (int i = 0; i < myHistoryArr.count; i++)
    {
        if ([seachField.text isEqualToString:myHistoryArr[i]])
        {
            [myHistoryArr removeObjectAtIndex:i];
        }
        
    }
    
    //用户搜索历史记录
    [myHistoryArr insertObject:seachField.text atIndex:0];
    
    
    //数组转化成data持久化
    NSData *encodemenulist = [NSKeyedArchiver archivedDataWithRootObject:myHistoryArr];
    [_defaults setObject:encodemenulist forKey:@"searchArrayData"];
    [_defaults synchronize];
    
    
    NSString *titleStr = [seachField.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    fenLeiDetailViewController *vc = [[fenLeiDetailViewController alloc] init];
    vc.tureTypeStr = @"search";
    vc.searchTitle = seachField.text;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];


    
}

- (void)handleTureGoodList :(UIButton *)sender {
    fenLeiDetailViewController *vc = [[fenLeiDetailViewController alloc] init];
    vc.tureTypeStr = @"search";
    vc.searchTitle = _hotListArry[sender.tag -100];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

@end
